package cn.cimoc.service.impl;

import cn.cimoc.mapper.UserMapper;
import cn.cimoc.model.JwtUser;
import cn.cimoc.model.po.TUser;
import cn.cimoc.util.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import cn.cimoc.constant.ConstantPool;
import cn.cimoc.service.JwtService;
import cn.cimoc.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author LGZ
 * @date 2021/11/20 16:47
 */
@Service
@Slf4j
public class JwtServiceImpl implements JwtService {

    @Value("${token.validPeriod}")
    private int days;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    UserMapper userMapper;

    @Override
    public String saveUserLoginInfo(UserDetails userDetails) {

        Map<String, String> map = new HashMap<>();
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        List<String> roles = new ArrayList<>();
        for (GrantedAuthority grantedAuthority: authorities) {
            if (grantedAuthority.getAuthority().startsWith(ConstantPool.ROLE_PREFIX)) {
                roles.add(grantedAuthority.getAuthority());
            }
        }
        JwtUser detail = (JwtUser)userDetails;
        map.put(ConstantPool.USERNAME, detail.getUsername());
        map.put(ConstantPool.ROLE, String.join(",", roles.toArray(new String[0])));
        map.put(ConstantPool.USER_ID, detail.getId().toString());


        // 生成新的token
        String token = JwtUtils.getToken(map);
        redisUtils.set(token, "", TimeUnit.DAYS.toSeconds(days));
        return token;
    }

    @Override
    public String getAvatar(String token) {
        Long uid = Long.parseLong(JwtUtils.verify(token).getClaim(ConstantPool.USER_ID).asString());
        TUser tUser = userMapper.selectById(uid);
        return tUser.getAvatar();
    }
}
